﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LMKJ.Classes;
using System.Collections;
using System.Text.RegularExpressions;

namespace LMKJ
{
    public partial class addshoppinglist : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                dateReqInit();
                existingItemsInit();
            }
        }

        protected void dateReqInit()
        {
            int thisYear = DateTime.Today.Year;

            for (int m = 1; m <= 12; m++)
            {
                monthDdl.Items.Add(m.ToString());
            }

            for (int y = thisYear; y <= thisYear + 1; y++)
            {
                yearDdl.Items.Add(y.ToString());
            }
        }

        protected void existingItemsInit()
        {
            ArrayList existingItems = DatabaseManager.RetrieveAllItemName();
            foreach (string item in existingItems)
            {
                existingItemsDdl.Items.Add(item);
            }
        }

        protected void monthDdl_SelectedIndexChanged(object sender, EventArgs e)
        {
            int monthNo;
            int dayNo = 0;

            if (monthDdl.SelectedItem.Text != "Month")
            {
                dayDdl.Enabled = true;
                yearDdl.Enabled = true;

                if (dayDdl.SelectedIndex > 1)
                {
                    dayNo = Convert.ToInt32(dayDdl.SelectedItem.Text);
                }

                dayDdl.Items.Clear();
                dayDdl.Items.Add("Day");

                monthNo = monthDdl.SelectedIndex;

                for (int d = 1; d <= 31; d++)
                {
                    dayDdl.Items.Add(d.ToString());
                    if (monthNo == 2 && d == 29)
                    {
                        break;
                    }
                    else if ((monthNo == 4 || monthNo == 6 || monthNo == 9 || monthNo == 11) && d == 30)
                    {
                        break;
                    }
                }

                if (dayDdl.Items.Count - 1 >= dayNo)
                {
                    dayDdl.SelectedIndex = dayNo;
                }
            }
            else if (monthDdl.SelectedItem.Text == "Month")
            {
                dayDdl.SelectedIndex = 0;
                yearDdl.SelectedIndex = 0;
                dayDdl.Enabled = false;
                yearDdl.Enabled = false;
            }
        }

        protected void addBtn_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                ShoppingList sl = new ShoppingList();
                sl.Nric = nricTbx.Text;
                sl.Date_req = yearDdl.SelectedItem.Text + "-" + monthDdl.SelectedItem.Text + "-" + dayDdl.SelectedItem.Text;

                int success = DatabaseManager.CreateShoppingList(sl);

                if (success == 1)
                {
                    int lid = DatabaseManager.RetrieveNewShoppingListId();

                    foreach (ListItem i in itemsListLbox.Items)
                    {
                        ItemList il = new ItemList();
                        il.List_id = lid;
                        string[] item = i.Text.Split('-');
                        il.Item_name = item[0].Trim();
                        il.Qty = Convert.ToInt32(item[1].Trim());

                        success = DatabaseManager.CreateItemList(il);
                    }

                    if (success == 1)
                    {
                        string jsPopup = "<script type='text/javascript'>" +
                            "alert('Successfully Created Shopping List!');" +
                            "window.location.href = 'searchshoppinglists.aspx';" +
                            "</script>";
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", jsPopup);
                    }
                }
            }
        }

        protected void cancelBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("searchshoppinglists.aspx");
        }

        protected void addItemToLboxBtn_Click(object sender, EventArgs e)
        {
            bool itemFound = false;

            foreach (ListItem i in itemsListLbox.Items)
            {
                if (i.Text.Split('-')[0].Trim().Equals(existingItemsDdl.SelectedItem.Text))
                {
                    itemFound = true;
                    break;
                }
            }

            if (!itemFound && Convert.ToInt32(quantityTbx.Text) > 0)
            {
                itemsListLbox.Items.Add(existingItemsDdl.SelectedItem.Text + " - " + quantityTbx.Text);
            }
        }

        protected void removeItemFromLboxBtn_Click(object sender, EventArgs e)
        {
            if (itemsListLbox.Items.Count > 0)
            {
                int[] removeItems = itemsListLbox.GetSelectedIndices();
                for (int i = removeItems.Length - 1; i >= 0; i--)
                {
                    itemsListLbox.Items.RemoveAt(removeItems[i]);
                }
            }
        }

        protected void fieldsValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (String.IsNullOrEmpty(nricTbx.Text.Trim())
                || monthDdl.SelectedIndex == 0 || dayDdl.SelectedIndex == 0 || yearDdl.SelectedIndex == 0)
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }

        protected void residentValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            Resident r = DatabaseManager.RetrieveResidentByNric(nricTbx.Text);

            if (r.Nric == null)
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }

        protected void dateValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (!(monthDdl.SelectedIndex == 0 || dayDdl.SelectedIndex == 0 || yearDdl.SelectedIndex == 0))
            {
                string selectedDate = string.Format("{0:0000}", yearDdl.SelectedItem.Text) +
                    string.Format("{0:00}", monthDdl.SelectedItem.Text) +
                    string.Format("{0:00}", dayDdl.SelectedItem.Text);
                string todayDate = string.Format("{0:0000}", DateTime.Now.Year.ToString()) +
                    string.Format("{0:00}", DateTime.Now.Month.ToString()) +
                    string.Format("{0:00}", DateTime.Now.Day.ToString());

                if (Convert.ToInt32(selectedDate) - Convert.ToInt32(todayDate) < 7)
                {
                    args.IsValid = false;
                }
                else
                {
                    args.IsValid = true;
                }
            }
        }

        protected void qtyValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            Regex NumbersOnly = new Regex("\\d+$");

            if (NumbersOnly.IsMatch(quantityTbx.Text))
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }
    }
}